import Vue from 'vue'
import VueRouter from 'vue-router'



// 二级路由
import layout from '@/views/layout'
import home from '@/views/layout/home.vue'
import categoray from '@/views/layout/categoray.vue'
import cart from '@/views/layout/cart.vue'
import user from '@/views/layout/user.vue'


// 导入store, 拿到token
import store from '@/store/index'


const login = () => import('@/views/login')
const search = () => import('@/views/search')
const searchList = () => import('@/views/search/list.vue')
const prodetail = () => import('@/views/prodetail')
const pay = () => import('@/views/pay')
const myorder = () => import('@/views/myorder')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: home
      },

      {
        path: '/categoray',
        component: categoray
      },

      {
        path: '/cart',
        component: cart
      },

      {
        path: '/user',
        component: user
      }
    ]
  },
  {
    path: '/login',
    component: login
  },
  {
    path: '/search',
    component: search
  },
  {
    path: '/searchlist',
    component: searchList
  },
  {
    path: '/prodetail/:id',
    component: prodetail
  },
  {
    path: '/pay',
    component: pay
  },
  {
    path: '/myorder',
    component: myorder
  }
]

const router = new VueRouter({
  routes
})

// 路由的前置守卫
// 所有的路由在真正被访问到之前(解析渲染组件之前),都会经过全局前置守卫
// 只有全局前置守卫放行了,才会到大要去的路由地址


// 定义一个数组, 专门用户存放所有需要权限访问的页面
const authUrls = ['/pay','/myorder']

router.beforeEach((to, from, next) => {
  // to : 到哪里去,完整路由信息对象(路径, 参数)
  // from: 从哪里来,从哪里来的完整路由信息对象 (路径, 参数)
  // next(): 是否放行
  // 1, next(): 直接放行,放心到to要去的路径
  // 2, next(路径): 进行拦截,拦截到next里面配置的路径
  // console.log(to, from, next);
  

  // 看to.path 是否在authUrls 中出现过
  if (!authUrls.includes(to.path)) { 
    // 非权限页面, 进行放行
    next()
    return 
  }

  // 权限页面, 需要判断token是否有值
  const token = store.getters.token
  if (token) {
    next()
  } else { 
    next('/login')
  }
 })

export default router
